package tmt.usercenter.web.controller.validtor;

import com.tmt.spring.validation.TmtCommonValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import tmt.usercenter.web.vo.user.EmailValidateInfo;

import java.lang.reflect.Field;

@Component
public class EmailValidateInfoValidator extends TmtCommonValidator<EmailValidateInfo> {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public boolean supports(Class<?> clazz) {
        return EmailValidateInfo.class.equals(clazz);
    }

    @Override
    public String selectMethodName(EmailValidateInfo obj, Field field, String methodName) {
        return methodName;
    }

    @Override
    public void validate(Object target, Errors errors) {
        EmailValidateInfo validateInfo = (EmailValidateInfo) target;
        if (!passwordEncoder.matches(validateInfo.getReceivedCode(), validateInfo.getSendCode())){
            errors.rejectValue("receivedCode", "error.EmailValidateInfo.receivedCode", "输入的验证码无效");
        }
    }

    @Override
    public boolean isRepeated(Object obj, String fieldName, Object fieldValue, boolean repeatable) {
        return false;
    }

}